<?php
require_once 'Zend/Db.php';
require_once 'Zend/Config/Ini.php';
require_once 'FtpHelper.php';
/**
 * 检查消费记录的正确性
 * @author Administrator
 *
 */
class xmlcommands{
    private function db()
    {   
        $params = array ('host' => 'db2.vsdn.bigtv.com.cn',
                 'port' => '3316',
                 'username' => 'jscn',
                 'password' => 'smpweb343306',
                 'charset' => 'UTF8',
                 'dbname'   => 'jscn');
        $db = Zend_Db::factory('PDO_MYSQL', $params);
        return $db;
    }
    
    function procTCommand()
	{
		$dir ="/tmp/xml/";
		if ($dh = opendir($dir)) {
	        while (($file = readdir($dh)) !== false) {
	        	if(strpos($file,".tar.gz"))
	        	{
	        		try{
	        			system("tar -xzvf $dir$file -C $dir");
	        			$this->procCommand($file);
	        		}
	        		catch (Exception $e){
	        			echo 'Caught exception: ',  $e->getMessage(), "\n";
	        		}	        		
	        	}
	        }
	        closedir($dh);
	    }
	}
    
    function procCommand($tfile)
	{
		$dir ="/tmp/xml/";
		if ($dh1 = opendir($dir)) {
	        while (($file1 = readdir($dh1)) !== false) {
	        	if(strpos($file1,".xml"))
	        	{
	        		try{
	        			$this->createEpg($file1,$tfile);
	        		}
	        		catch (Exception $e){
	        			echo 'Caught exception: ',  $e->getMessage(), "\n";
	        		}	        		
	        	}
	        }
	        closedir($dh1);
	    }
	}
	
	function createEpg($xmlfile,$tfile)//从文件导入epg信息
    {
		//$filename = "/tmp/c.xml";
		echo $xmlfile;
		$dir ="/tmp/xml/";
		if($xmlfile){
			try{
				$ok = false;
				$db = $this->db();
				$fp2 = fopen($dir.$xmlfile, 'r');
				$xmldata = fread($fp2, filesize($dir.$xmlfile));
				fclose($fp2);
				$doc = new DOMDocument();
				$doc->loadXML($xmldata);
				$items = $doc->getElementsByTagName("item");
				print_r($items);
				//$eventidbase = 0;//偏移值
				//$timebase = "";
				//$realeventid = 0;//初始值为0
				foreach($items as $item)
				{
					$starttime = $item->getAttribute("starttime");
					$endtime = $item->getAttribute("endtime");
					$cs = $item->getAttribute("cs");
					$db->query("insert into tmpxml (f, s, e, cs) values (:f, :s, :e, :cs)",array("f"=>$tfile,"s"=>$starttime,"e"=>$endtime,"cs"=>$cs));
					echo $starttime."\n";
		            $ok = true;
		        }
		        if($ok)
		        {
		        	//$db->query("delete from epg where flag = 1");
		        	unlink($dir.$xmlfile);
		        }
			}
			catch (Exception $e){
				echo 'Caught exception: ',  $e->getMessage(), "\n";
				//syslog(LOG_INFO, ": commands - clearRecycleCommand." .$e->getMessage());
			}
    	}
    }
}
$cmd=$argv[1]; 
if($cmd=="p"){//清节目单
	$test = new xmlcommands();
	$test->procTCommand();
	//syslog(LOG_INFO, ": commands - clearEpgCommand.");
}